<?php


namespace app\admin\system\controller;


use app\admin\system\logic\AdminLogic;
use app\admin\system\logic\RoleLogic;
use app\common\controller\BaseAdminController;
use app\common\service\PasswordService;
use app\model\SysAdmin;
use core\exception\BadException;
use core\utils\RandomUtil;

class AdminController extends BaseAdminController
{

    protected $noNeedRight = [
    ];

    protected function init()
    {
        parent::init();
        $this->logic = new AdminLogic();
    }


    public function list()
    {
        $where = [];
        $this->form['keyword'] && $where[] = ['username|mobile|nickname', 'like', "%{$this->form['keyword']}%"];
        if (!is_null($this->form['filterAvatar']) && $this->form['filterAvatar'] != "") {
            if ($this->form['filterAvatar'] == 0) {
                $where[] = ['avatar', '=', ''];
            } else {
                $where[] = ['avatar', '<>', ''];
            }
        }
        if ($this->form['login_start'] && $this->form['login_end']) {
            $where[] = ['login_time', 'between', $this->form['login_start'], $this->form['login_end']];
        }

        $query = $this->logic->search($where);
        if ($this->form->needOrder()) {
            $query->order($this->form->getSortField(), $this->form->getOrder());
        } else {
            $query->order('id', 'desc');
        }

        $data = $this->logic->getPageList($query);
        $role_ids = [];
        array_walk($data['rows'], function (&$v) use (&$role_ids) {
            $role_ids = array_merge($role_ids, $v['role_ids']);
        });
        $roleLogic = new RoleLogic();
        $roleMap = $roleLogic->where('id', 'in', $role_ids)
            ->column('name', 'id');
        array_walk($data['rows'], function (&$v) use ($roleMap) {
            $roles = [];
            foreach ($v['role_ids'] as $id) {
                if ($rr = $roleMap[$id] ?? "") {
                    $roles[] = $rr;
                }
            }
            $v['roles'] = $roles;
        });

        return $this->success($data);
    }

    public function add()
    {
        $data = request()->post();
        $salt = RandomUtil::randomLetter(10);
        $data['password'] = PasswordService::getPassword("123456", $salt);
        $data['salt'] = $salt;
        if ($this->validate) {
            if (!$this->validate->scene('add')->check($data)) {
                return $this->error($this->validate->getError());
            }
        }
        $where = [
            'username' => $data['username'],
        ];
        if (isset($data['mobile']) && 'mobile') {
            $where[] = ['mobile' => $data['mobile']];
        }
        $user = $this->logic->getModel()->whereOr($where)->find();
        if ($user) {
            return $this->error("登录账号或者手机号已存在");
        }
        $result = $this->logic->save($data);
        if ($result) {
            return $this->success();
        } else {
            return $this->error();
        }
    }

    public function update()
    {
        $data = request()->post();
        $id = request()->input('id');
        $salt = RandomUtil::randomLetter(10);
        $data['password'] = PasswordService::getPassword("123456", $salt);
        $data['salt'] = $salt;
        if ($this->validate) {
            if (!$this->validate->scene('add')->check($data)) {
                return $this->error($this->validate->getError());
            }
        }
        $result = $this->logic->update($data, [$this->idKey => $id]);
        if ($result) {
            return $this->success();
        } else {
            return $this->error();
        }
    }

    public function resetPwd()
    {
        $id = input('id');
        if (!$id) {
            throw new BadException("参数错误");
        }
        $salt = RandomUtil::randomLetter(10);
        $data['password'] = PasswordService::getPassword(123456, $salt);
        $data['salt'] = $salt;
        $this->logic->update($data, [
            'id' => $id
        ]);
        return $this->success();
    }

    public function updateRole()
    {
        $id = input($this->idsKey, input($this->idKey));
        if (!$id) {
            throw new BadException("参数错误");
        }
        $data['role_ids'] = implode(',', input('role_ids'));
        $this->logic->update($data, [
            'id' => $id
        ]);
        return $this->success();
    }

    public function updatePwd()
    {
        if (!input('userPassword') || !input('newPassword')) {
            throw new BadException("参数错误");
        }
        $userPassword = input('userPassword');

        $user = SysAdmin::where([
            'id' => request()->uid
        ])->field(['id', 'nickname', 'password', 'salt', 'status', 'google_auth_secret'])->find();
        if (!$user) {
            throw new BadException("系统异常,查询不到用户信息");
        }
        if (!PasswordService::checkPassword($userPassword, $user['password'], $user['salt'])) {
            throw new BadException("当前密码输入错误");
        }

        $newPassword = input('newPassword');
        $salt = RandomUtil::randomLetter();
        $data['password'] = PasswordService::getPassword($newPassword, $salt);
        $data['salt'] = $salt;
        $this->logic->update($data, [
            'id' => request()->uid
        ]);
        return $this->success();
    }

    public function updateInfo()
    {
        if (!input('nickname')) {
            throw new BadException("参数错误");
        }
        $this->logic->update([
            'nickname' => input('nickname')
        ], [
            'id' => request()->uid
        ]);
        return $this->success();
    }

    public function loginInfo()
    {
        $data = $this->logic->getModel()->withoutField([
            'salt',
            'password',
        ])
            ->where([
                'id' => request()->uid
            ])
            ->find();
        return $this->success($data);
    }
}